package ws

import (
	"context"
	"fmt"
	"gim-server/model"
	"gim-server/sdk"
)

type MsgDto struct {
	Event    string      `json:"event"`
	Data     interface{} `json:"data,omitempty"`
}

type ImageMsg struct {
	Url    string `json:"url"`
	Width  int    `json:"width"`
	Height int    `json:"height"`
}

type VideoMsg struct {
	Url    string `json:"url"`
	Cover  string `json:"cover"`
	Dur    int64  `json:"dur"`
	Width  int    `json:"width"`
	Height int    `json:"height"`
}

type AudioMsg struct {
	Url string `json:"url"`
	Dur int64  `json:"dur"`
}

type GeoMsg struct {
	Lat      float64 `json:"lat"`
	Lng      float64 `json:"lng"`
	Country  string  `json:"country"`
	Province string  `json:"province"`
	City     string  `json:"city"`
	Area     string  `json:"area"`
	Addr     string  `json:"addr"`
}

func SendC2cMsg(msg *model.TbC2cMsgRecord, notPush bool, pushTitle string, pushContent string) {
	db := sdk.DB(context.Background())
	cvs := make([]*model.TbConversation, 0)
	db.Find(&cvs, "(from_uid = ? and to_uid = ?) or (from_uid = ? and to_uid = ?)", msg.FromUID, msg.ToUID, msg.ToUID, msg.FromUID)
	var fromCvs *model.TbConversation
	var toCvs *model.TbConversation
	for _, item := range cvs {
		if item.FromUID == msg.FromUID {
			fromCvs = item
		} else {
			toCvs = item
		}
	}
	fromConn, ok := imClients[fmt.Sprintf(imKeyFmt, msg.FromUID)]
	if ok {
		msg := new(model.TbC2cMsgRecord)
		if err := db.Where("((from_uid = ? and to_uid = ?) or (from_uid = ? and to_uid = ?)) and del_uid not in ?",
			fromCvs.FromUID, fromCvs.ToUID, fromCvs.ToUID, fromCvs.FromUID, []string{"-1", fromCvs.FromUID}).
			Order("id desc").First(msg).Error; err == nil {
			fromCvs.LastMsg = msg
		}
		_ = fromConn.WriteJSON(&MsgDto{
			Event: SybConversationUpdate,
			Data:  fromCvs,
		})
	}
	var n int64
	db.Model(new(model.TbC2cMsgRecord)).Where("to_uid = ? and readed = ? and del_uid not in ?", msg.ToUID, false, []string{"-1", msg.ToUID}).Count(&n)
	conn, ok := imClients[fmt.Sprintf(imKeyFmt, msg.ToUID)]
	if ok {
		//通知对方收到新消息
		_ = conn.WriteJSON(&MsgDto{
			Event: SybNewC2cMsg,
			Data:  msg,
		})
		//通知对方会话更新
		msg := new(model.TbC2cMsgRecord)
		if err := db.Where("((from_uid = ? and to_uid = ?) or (from_uid = ? and to_uid = ?)) and del_uid not in ?",
			toCvs.FromUID, toCvs.ToUID, toCvs.ToUID, toCvs.FromUID, []string{"-1", toCvs.ToUID}).
			Order("id desc").First(msg).Error; err == nil {
			toCvs.LastMsg = msg
		}
		_ = conn.WriteJSON(&MsgDto{
			Event: SybConversationUpdate,
			Data:  toCvs,
		})
		//通知对方未读消息数量
		_ = conn.WriteJSON(&MsgDto{
			Event: SybUnreadCount,
			Data:  n,
		})
	}
	if !notPush {
		TpnsPush(msg.ToUID, pushTitle, pushContent, int(n), 0)
	}
}
